import os
import json
import openai
from datetime import datetime, timedelta
from typing import Dict, Optional, List

def text_reply(content, syst='FGAI智能助手'):
    model = 'qwen-turbo-latest' # 'gpt-4o-mini'
    api_key = 'xxxx'
    base_url = 'xxxx'
    client = openai.OpenAI(
        api_key=api_key,
        base_url=base_url,
    )
    response = client.chat.completions.create(
            model=model,
            messages=[
                {'role': 'system', 'content': syst},
                {'role': 'user', 'content': content}
            ],
            temperature=0.7
        )
    print(response.choices[0].message.content)
    return response.choices


class WeatherAgent:
    def __init__(self):
        self.tool_definitions = [
            {
                'type': 'function',
                'function': {
                    'name': 'get_current_date',
                    'description': '获取当前系统日期',
                    'parameters': {'type': 'object', 'properties': {}}
                }
            },
            {
                'type': 'function',
                'function': {
                    'name': 'get_weather',
                    'description': '查询指定地点的实时天气',
                    'parameters': {
                        'type': 'object',
                        'properties': {
                            'location': {
                                'type': 'string',
                                'description': '城市名称，如：北京、上海'
                            }
                        },
                        'required': ['location']
                    }
                }
            }
        ]
    
    def _call_tool(self, tool_name, parameters):
        '''工具执行分发'''
        if tool_name == 'get_current_date':
            return datetime.now().strftime('%Y-%m-%d')
        elif tool_name == 'get_weather':
            return self._get_weather(parameters.get('location', 'default'))
        return None

    def _get_weather(self, location):
        '''天气查询工具实现'''
        # 模拟数据
        weather_infos = {
            '北京': 25,
            '上海': 26,
            '广州': 27,
            'default': 20
        }
        return {'temp': weather_infos[location]}

    def process_query(self, user_input):
        '''完整的处理流程'''
        # 第一步：调用大模型进行工具选择
        api_key = '<用户的 API Key>'
        base_url = 'https://dashscope.aliyuncs.com/compatible-mode/v1'
        client = openai.OpenAI(
            api_key=api_key,
            base_url=base_url,
        )
        response = client.chat.completions.create(
            model='qwen-turbo-latest',
            messages=[{'role': 'user', 'content': user_input}],
            tools=self.tool_definitions,
            tool_choice='auto'
        )

        print('response: ', response)

        tool_calls = response.choices[0].message.tool_calls # None
        print('意图工具列表：', tool_calls)
        if not tool_calls:
            return '抱歉，我暂时无法处理这个请求'

        results = []
        for tool_call in tool_calls:
            tool_name = tool_call.function.name
            parameters = json.loads(tool_call.function.arguments)
            print('工具名称与参数：', tool_name, parameters)
            result = self._call_tool(tool_name, parameters)
            results.append({
                'tool_name': tool_name,
                'content': result
            })
        return results


# 测试多轮对话
if __name__ == '__main__':
    agent = WeatherAgent()
    query = '广州的天气怎么样？'
    # query = '今天'
    response = agent.process_query(query)
    print(f'返回结果：{response}')
   